package com.link.base.base.saleactivity.controller;

import com.link.base.base.email.model.EmailInfo;
import com.link.base.base.email.service.EmailService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.service.BasicService;
import com.link.core.util.*;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 手机验证码
 * @author wangdawei
 * @date 2018/6/1
 */
@Controller
@RequestMapping("/link/phoneMsgs")
public class PhoneMsgController extends BasicController<EmailInfo> {
    /**验证码缓存时key值后缀*/
    private static final String VCODECACHE_KEYSUFFIX = "#MarketingCampaignVCode";
    /**验证码缓存冷却状态后缀*/
    private static final String VCODECD_KEYSUFFIX = "#MarketingCampaignCDVCode";
    /**验证码有效时间*/
    private static final int VCODE_EFFECTIVETIME = 300;
    /**获取验证码冷却时间*/
    private static final int VCODE_COOLDOWNTIME = 60;
    @Resource
    private EmailService emailService;

    @Override
    public BasicService<EmailInfo> getBasicService() throws Exception {
        return emailService;
    }

    /**
     * 请求发送验证码入口
     * @author wangdawei
     * @date 2018/6/1
     * @param mobilePhone
     * @return
     */
    @RequestMapping("/getVerifyCode")
    @ResponseBody
    public Map<String, Object> sendVerificationCode(@RequestParam String mobilePhone) {
        Map<String, Object> result = new HashMap<String, Object>(5);
        LinkRedisClient  jedis = RedisUtil.getJedis();
        String regExp = "^1[3|4|5|7|8][0-9]\\d{4,8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(mobilePhone);

        if (StringUtils.isBlank(mobilePhone)) {
            result.put("success", false);
            result.put("errorMsg", "手机号码不能为空");
            return result;
        } else if (!m.find()) {
            result.put("success", false);
            result.put("Type", "warning");
            result.put("errorMsg", "手机号码格式不正确，请重新输入");
        }

        String vCode = genVCode();
        try {
            if (!jedis.exists(mobilePhone + VCODECD_KEYSUFFIX)) {
                String resultStr = this.sendVCode(mobilePhone, vCode);
                result = JsonUtil.fromJsonStringToT(resultStr, Map.class);
                setVCodeToCache(vCode, mobilePhone);
                result.put("success", true);
            } else {
                result.put("success", false);
                result.put("errorMsg", "1分钟内不能重复发放验证码");
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("Type", "error");
            result.put("result", e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return result;
    }

    /**
     * 比较验证码
     * @author wangdawei
     * @date 2018/6/1
     * @param mobilePhone
     * @param code
     * @return
     */
    @RequestMapping("/codeCompare")
    @ResponseBody
    public Map<String, Object> codeCompare(@RequestParam String code, @RequestParam String mobilePhone) {
        Map<String, Object> result = new HashMap<String, Object>(5);
        LinkRedisClient jedis = RedisUtil.getJedis();
        try {
            String codeStr = jedis.get(mobilePhone + VCODECACHE_KEYSUFFIX);
            if (codeStr != null) {
                if (codeStr.equals(code)) {
                    result.put("result", "Y");
                } else {
                    result.put("result", "N");
                }
            } else {
                result.put("result", "N");
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("Type", "error");
            result.put("result", e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return result;
    }

    /**
     * 优惠券领取成功短信通知
     * @author wangdawei
     * @param mobilePhone
     * @param name
     * @param addr
     * @param codeid      营销活动id
     * @param id1         客户id
     * @return
     */
    private String sendAcceptSuccessMsg(String mobilePhone, String name, String addr, String codeid, String id1) {
        LinkedHashMap<String, String> param = new LinkedHashMap<String, String>();
        param.put("name", name);
        param.put("addr", addr);
        param.put("codeid", codeid);
        param.put("id1", id1);
        String couponMsgTemplate = PropertyUtil.getCommonProperty(RedisConstants.key_couponMsgTemplate);
        return SendSmsUtil.sendMsg(mobilePhone, couponMsgTemplate, param, "");
    }

    /**
     * 获取缓存中的验证码
     * @author wangdawei
     * @param mobilePhone 手机号
     * @param delFlag     是否删除，true为删除
     * @return
     */
    private String getVCodeFromCache(@JsonParam String mobilePhone,@JsonParam  boolean delFlag) {
        LinkRedisClient  jedis = RedisUtil.getJedis();
        String redisKey = mobilePhone + VCODECACHE_KEYSUFFIX;
        String vCode = jedis.get(redisKey);
        if (delFlag) {
            jedis.del(redisKey);
        }
        RedisUtil.returnResource(jedis);
        return vCode;
    }

    /**
     * 验证码保存到redis
     * @author wangdawei
     * @param vCode
     * @param mobilePhone
     */
    private void setVCodeToCache(String vCode, String mobilePhone) {
        String redisKey = mobilePhone + VCODECACHE_KEYSUFFIX;
        String redisCDKey = mobilePhone + VCODECD_KEYSUFFIX;
        LinkRedisClient  jedis = null;
        try {
            jedis = RedisUtil.getJedis();
            jedis.set(redisKey, vCode);
            jedis.set(redisCDKey, vCode);
            //五分钟内有效
            jedis.expire(redisKey, VCODE_EFFECTIVETIME);
            // 一分钟冷却时间
            jedis.expire(redisCDKey, VCODE_COOLDOWNTIME);
        } finally {
            RedisUtil.returnResource(jedis);
        }
    }

    /**
     * 发送验证码
     * @author wangdawei
     * @param mobilePhone
     * @param vCode
     * @return 验证码
     * @throws Exception
     */
    private String sendVCode(String mobilePhone,String vCode) throws Exception {
        LinkedHashMap<String, String> param = new LinkedHashMap<String, String>();
        param.put("no", vCode);
        String vCodeMsgTemplate = PropertyUtil.getCommonProperty(RedisConstants.key_vCodeMsgTemplate);
        return SendSmsUtil.sendMsg(mobilePhone, vCodeMsgTemplate, param, "VertificationCode");
    }

    /**
     * 生成随机验证码
     * @author wangdawei
     * @return
     */
    private String genVCode() {
        Random rd = new Random();
        String vCode = "";
        int  codeLen = 6;
        for (int i = 0; i < codeLen; i++) {
            vCode += String.valueOf(rd.nextInt(10));
        }
        return vCode;
    }
}
